'use strict';

/**
 * @ngdoc function
 * @name jgappApp.controller:ChatChatroomCtrl
 * @description
 * # ChatChatroomCtrl
 * Controller of the jgappApp
 */
angular.module('jgappApp')
    .controller('ChatChatroomCtrl', function (DataService, $interval, $filter, RongYService, $timeout, ChatStatus, $location, openApi, $scope, $q, $rootScope, newMessageEventService, RongUtil, Groups, ChatUser, $routeParams, Util) {
        var vm = this;
        vm.msg="";
        var isIOS = Util.getPlatform() == "ios";
        var isAndroid = Util.getPlatform() == "android";
        vm.hisMsgs = []
        this.goback = function () {
            Util.goBack()
        };
        this.goDetail = function (id) {
            $location.path("addressbook/userdetail/" + id)
        }
        var targetId = $routeParams.targetId
        var conversationType = $routeParams.conversationType
        vm.conversationType = conversationType

        vm.targetId = targetId
        var newMsgCallBack = function (d, data) {
            var jsonMsg = JSON.parse(data);
            if (targetId == jsonMsg.targetId) {
                // 清除已读
                RongYService.clearMessagesUnreadStatus(targetId, conversationType).then(function (data) { })
                var tmpMsg = RongUtil.resolveMsg(jsonMsg);
                vm.hisMsgs.push(tmpMsg);
                _setPosition()
            }
        };
        newMessageEventService.listen(newMsgCallBack);
        // 获取历史信息
        this.getlastMsg = function () {
            // var defer = $q.defer();
            var oldestMessageId = vm.hisMsgs[0] && vm.hisMsgs[0].messageId;
            // oldestMessageId = 97;
            var param = {};
            param.conversationType = conversationType
            param.targetId = targetId
            param.count = 10
            param.oldestMessageId = oldestMessageId
            RongYService.getHistoryMessages(param).then(function (data) {
                if (data && data.length > 0) {
                    var result = [],
                        tmp;
                    for (var i = data.length - 1; i >= 0; i--) {
                        tmp = data[i];
                        tmp = RongUtil.resolveMsg(tmp);
                        result.push(tmp);
                    }
                    var hisArr = result.concat(vm.hisMsgs);
                    vm.hisMsgs = hisArr;
                    // defer.resolve()
                } else {
                    Util.Toast("没有更多信息");
                }
            })
            // return defer.promise
        };
        // 详情
        this.goRoomDetail = function () {
            ChatStatus.setTargetId($routeParams.targetId);
            ChatStatus.setChatType(conversationType);
            $location.path("/chat/groupDetail/" + targetId);
        };

        this.buildUrl = function (type) {
            var tmpName;
            switch (type) {
                case 'RC:TxtMsg':
                    tmpName = 'txt';
                    break;
                case 'RC:ImgMsg':
                    tmpName = 'img';
                    break;
                case 'RC:DizNtf':
                    tmpName = 'diz';
                    break;
                case 'RC:LBSMsg':
                    tmpName = 'lbs';
                    break;
                case 'RC:ImgTextMsg':
                    tmpName = 'imgtext';
                    break;
                case 'RC:VcMsg':
                    tmpName = 'vc';
                    break;
                default:

            }
            return 'views/message/' + tmpName + '.html';
        }
        var src = "cordovaIMVoice.amr";
        // var path = "/storage/sdcard0/";  //
        if (cordova.file) {

            var path = cordova.file.externalApplicationStorageDirectory;
            if (isIOS) {
                path = cordova.file.documentsDirectory;
                src = "cordovaIMVoice.wav";
            }
        }
        var mediaRec;

        function getMediaURL(s) {
            if (device.platform.toLowerCase() === "android") return path + s;
            return (path + s).replace('file://', '');
        }

        function getNewMediaURL(s) {
            if (device.platform.toLowerCase() === "android") return path + s;
            return "documents://" + s;
        }

        $scope.play = function (message) {
            var voiFile = message.content.voicePath
            console.log('start play!' + voiFile);
            message.voiceplaying = true;
            mediaRec = new Media(voiFile,
                // 成功操作
                function () {
                    console.log("play():Audio Success");
                    message.voiceplaying = false;
                    mediaRec.release();
                    $scope.$apply()
                },
                // 失败操作
                function (err) {
                    message.voiceplaying = false;
                    $scope.$apply()
                    console.log("play():Audio Error: " + JSON.stringify(err));
                }
            );
            //开始播放录音
            mediaRec.play({ numberOfLoops: 1 });
            return false;

        };

        $scope.openImage = function (img) {
            $scope.src = img
            Util.showFile($scope)
        }
        $scope.closefile = function () {
            $scope.src = "";
            Util.hideFile();
        };
        var appendNewMsg = function (msg, flag) {
            // $scope.lstResult = JSON.stringify(msg);
            var curMsg = RongUtil.resolveMsg(msg);
            //消息此时未发送成功，可以加入样式标明；成功后更新样式
            vm.hisMsgs.push(curMsg);
            _setPosition()
        }
        this.emojipicker = function (data) {
            console.log(data)
            vm.msg += $filter("colonToCode")(data)
        };
        var getLatestMsg = function (targetid, ctype) {
            var param = {};
            param.conversationType = ctype
            param.targetId = targetId
            param.count = 10
            RongYService.getLatestMessages(param).then(function (data) {
                var result = [],
                    tmp;
                for (var i = data.length - 1; i >= 0; i--) {
                    tmp = data[i];
                    tmp = RongUtil.resolveMsg(tmp);
                    result.push(tmp);
                }
                vm.hisMsgs = result;
                // 滚动到底部
                _setPosition()
            })
        }

        this.getPhoto = function (type) {
            var sourceType = type ? Camera.PictureSourceType.SAVEDPHOTOALBUM : Camera.PictureSourceType.CAMERA
            var options = {
                quality: 100,
                targetWidth: 320,
                targetHeight: 320,
                sourceType: sourceType,
                // destinationType: Camera.DestinationType.DATA_URL
                destinationType: Camera.DestinationType.FILE_URI
            };

            var cameraError = function (err) {

            };

            var cameraSuccess = function (imageURI) {
                var picPath = Util.addTimesamp(imageURI);
                console.log("getPicture:" + picPath);
                if (isIOS) {
                    picPath = imageURI.replace('file://', '');
                }
                var param = {
                    conversationType: conversationType,
                    targetId: targetId,
                    imagePath: picPath,
                    extra: "this is a extra text"
                }
                RongYService.sendImageMessage(param).then(function (data) {
                    getLatestMsg(targetId, conversationType);
                })
            }
            navigator.camera.getPicture(cameraSuccess, cameraError, options);
        }
        this.sendMsg = function () {
            var msgContent = vm.msg;
            if (!msgContent) {
                return
            }
            var param = {
                conversationType: conversationType,
                targetId: targetId,
                text: vm.msg,
                extra: "this is a extra text"
            }
            RongYService.sendTextMessage(param).then(function (data) {
                appendNewMsg(data.result.message, true);
                vm.msg = "";
                vm.resetinput();
            })
        }
        var _setPosition = function () {
            $timeout(function () {
                var $chatroom = angular.element(document.querySelector('.chatroom'))[0];
                var $chatroomH = $chatroom.offsetHeight
                var $elem = angular.element(document.querySelector('.msg-wrapper'))[0]
                var $elmH = $elem.offsetHeight
                if ($elmH > $chatroomH) {
                    $chatroom.scrollTop = $elmH
                }
            }, 200)
        }
        //开始录音
        function initmedia(callback) {
            //定义录音文件保存名称及位置（android默认保存在根目录）
            //var src = "sounds/cordovaIMVoice.amr";
            //实例化录音类
            if (mediaRec) {
                mediaRec.release();
            }
            mediaRec = new Media(getNewMediaURL(src),
                // 录音执行函数
                function () {
                    if (callback) {
                        callback()
                    }
                },
                // 录音失败执行函数
                function (err) {
                    console.log("start():Audio Error: " + JSON.stringify(err) + "----" + getMediaURL(src));
                }
            );
        }
        this.resetinput = function () {
            vm.showemojiBtn(1);
            vm.showmoreBtn(1);
            vm.showvoicebtn(1);
            vm.showkeyBoardbtn(0)
            vm.ifshowemoji = false
            vm.showvoicetext = false
            vm.showMoreInput = false
        }
        this.clickvoice = function () {
            this.resetinput();
            vm.showkeyBoardbtn(1)
            vm.showvoicebtn(0)
            vm.showemojiBtn(0);
            vm.showvoicetext = true;
            vm.showtext = false
            vm.ifhidesendBtn = true
        };
        this.clickkeyBoard = function () {
            this.resetinput();
            vm.ifhidesendBtn = false
        }
        this.clickmore = function () {
            this.resetinput();
            vm.showMoreInput = true
        };
        this.clickemoji = function () {
            this.resetinput();
            vm.ifshowemoji = true
            vm.ifhidesendBtn = false
        }
        this.showmoreBtn = function (type) {
            vm.ifshowmoreBtn = !!type
        }
        this.showemojiBtn = function (type) {
            vm.ifemojiinput = !!type
        }
        this.showvoicebtn = function (type) {
            vm.ifshowvoicebtn = !!type
            vm.showtext = true
        }
        this.showkeyBoardbtn = function (type) {
            vm.ifshowkeyBoardbtn = !!type
        }
        this.resetinput()
        //为按钮绑定  touchstart(点击) 事件
        this.startRecord = function () {

            //实例化录音类
            initmedia();
            //开始录音
            mediaRec.startRecord();
            // 显示录音图标
            vm.voiceinputing = true;
            return false;

        };
        //为按钮绑定 touchend(手势离开)事件
        this.sendVoiceMessage = function () {
            if (mediaRec) {
                //结束录音
                mediaRec.stopRecord();
                //释放系统底层的音频播放资源
                mediaRec.release();

            }
            // 隐藏录音图标
            vm.voiceinputing = false;
            //需要播放的录音的路径
            //实例化录音类
            mediaRec = new Media(getMediaURL(src),
                // 成功操作
                function () {
                    console.log("touchend():Audio Success");
                },
                // 失败操作
                function (err) {
                    console.log("touchend():Audio Error: " + err.code);
                }
            );

            //开始播放录音
            mediaRec.play();
            mediaRec.stop();
            var timerDur = $interval(function () {
                var dur = mediaRec.getDuration();
                if (dur > 0) {
                    $interval.cancel(timerDur);
                    console.log('mediaRec.getDuration():' + dur);
                    console.log('mediaRec.src:' + mediaRec.src);
                    var tmpPath = mediaRec.src;
                    if (isIOS) {
                        tmpPath = path + src;
                    }
                    tmpPath = tmpPath.replace('file://', '');
                    console.log('tmpPath:' + tmpPath);
                    var param = {
                        conversationType: conversationType,
                        targetId: targetId,
                        // voicePath:  '/storage/sdcard0/6599.amr',
                        voicePath: tmpPath,
                        duration: dur,
                        extra: "99 extra voice"
                    }
                    RongYService.sendVoiceMessage(param).then(function (data) {
                        mediaRec.release();
                        window.resolveLocalFileSystemURL(tmpPath, function (dir) {
                            dir.getFile(src, { create: false }, function (fileEntry) {
                                fileEntry.remove(function () {
                                    // The file has been removed succesfully
                                    console.log('removeFile2:' + JSON.stringify(success));
                                }, function (error) {
                                    // Error deleting the file
                                    console.log('removeFile2 err:' + JSON.stringify(error));
                                }, function () {
                                    // The file doesn't exist
                                });
                            });
                        });
                        appendNewMsg(data.result.message, true);
                    })
                }
            }, 100, 20);

            return false;
        };
        //为按钮绑定 touchmove(手势移动) 事件
        this.voicemove = function (e) {
            e.preventDefault();
            return false;

        };
        var init = function () {
            $scope.targetId = targetId;
            // 清除已读
            RongYService.clearMessagesUnreadStatus(targetId, conversationType).then(function (data) { });
            // 获取消息总数
            RongYService.getTotalUnreadCount().then(function (data) {
                // 是否显示角标
                $rootScope.haveMsgs = !!data
            });
            // 申请录音权限
            initmedia();
            $timeout(function () {
                if (mediaRec) {
                    mediaRec.startRecord();
                    //释放系统底层的音频播放资源
                    mediaRec.release();
                }
            }, 1000)

            getLatestMsg(targetId, conversationType);

        }

        if (ChatUser.isEmpty()) {
            DataService.getData(openApi.getuserinfo).then(function (data) {
                ChatUser.set(data);
                init();
            });
        } else {
            init();
        }
        // 根据会话类型获取title
        if (conversationType == ChatStatus.PRIVATE) {
            var userObj = ChatUser.get(targetId);
            if (userObj) {
                vm.title = userObj["name"]
            }
        } else if (conversationType == ChatStatus.GROUP) {
            var userObj = Groups.get(targetId);
            if (userObj) {
                vm.title = userObj["groupName"]
            }
        }

        // 监听消息发送状态
        var newMsgStatusCallBack = function (d, statusObj) {
            console.log(statusObj);
            vm.hisMsgs.forEach(function (item, index) {
                if (item.messageId == statusObj.messageId) {
                    switch (statusObj.status) {
                        case "success":
                            item.sentStatus = "SENT";
                            break;
                        case "error":
                            item.sentStatus = "FAILED";
                            break;
                    }
                }
            });
            $scope.$apply();
        }
        newMessageEventService.statusListen(newMsgStatusCallBack);
    });
